# Tool 系统 Prompt 详解

> **一句话摘要**：40 个工具的 prompt 设计通过"工具引导路由网络"互相推荐，配合延迟加载机制和动态 prompt 生成，实现精准的工具选择与高效的 token 使用。

> 核心文件：`src/tools/*/prompt.ts`、`src/tools.ts`

## 一、工具全景（40 个工具目录）

### 核心文件操作

| 工具 | Prompt 要点 |
|------|-----------|
| **Read** | 必须绝对路径；支持图片/PDF/Notebook；默认读 2000 行 |
| **Edit** | 必须先 Read 再 Edit；`old_string` 必须唯一；优先 Edit 而非 Write |
| **Write** | 已有文件必须先 Read；优先 Edit（只发 diff）；禁止无故创建 .md |
| **NotebookEdit** | 0-indexed cell；支持 replace/insert/delete |

### 搜索工具

| 工具 | Prompt 要点 |
|------|-----------|
| **Glob** | 支持 `**/*.js` 模式；按修改时间排序；开放搜索用 Agent |
| **Grep** | 基于 ripgrep；**ALWAYS 用 Grep，NEVER 用 bash grep**；3 种输出模式 |

### Shell 执行

| 工具 | Prompt 要点 |
|------|-----------|
| **Bash** | **最长最复杂的 prompt**（~400 行生成逻辑）；强制用专用工具替代 cat/grep/find 等；含 Git Safety Protocol + PR 创建流程 + Sandbox 配置 |
| **PowerShell** | PS 5.1 vs 7+ 语法差异；Read-Host 等交互命令会阻塞 |

### Agent/多代理

| 工具 | Prompt 要点 |
|------|-----------|
| **Agent** | 6 种 subagent_type；"像聪明同事一样 brief"；并行启动多个 |
| **SendMessage** | 纯文本输出对其他 agent 不可见，**必须用 SendMessage 通信** |
| **TeamCreate** | 任务所有权通过 TaskUpdate(owner) 分配；闲置是正常状态 |

### 任务管理

| 工具 | Prompt 要点 |
|------|-----------|
| **TaskCreate** | 3+ 步骤时使用；`activeForm` 用于 spinner 显示 |
| **TaskUpdate** | 完成后标 completed；未完成不要标 completed |
| **TodoWrite** | V1 版本；complex multi-step 时使用 |

### 计划模式

| 工具 | Prompt 要点 |
|------|-----------|
| **EnterPlanMode** | 非琐碎任务主动使用；GOOD/BAD 对比示例 |
| **ExitPlanMode** | 不要用 AskUserQuestion 问"计划 OK 吗"——用 ExitPlanMode |

### Web 工具

| 工具 | Prompt 要点 |
|------|-----------|
| **WebFetch** | 优先用 MCP/gh CLI；125 字符引用限制；15 分钟缓存 |
| **WebSearch** | **CRITICAL**: 必须包含 Sources 部分；动态插入当前年月 |

### 调度工具

| 工具 | Prompt 要点 |
|------|-----------|
| **CronCreate** | 标准 5-field cron；**避免 :00 和 :30 整点**；7 天自动过期 |
| **Sleep** | 优先于 `Bash(sleep)`；会收到 `<tick>` 周期性检查 |

## 二、Bash Prompt 完整结构解析

Bash prompt 是所有工具中最长、最复杂的（`getSimplePrompt()` 约 370 行），由多个动态拼接段组成：

### 2.0.1 整体骨架

```
┌──────────────────────────────────────┐
│ 1. 描述 + 工具替代指令               │  ← 强制用 Glob/Grep/Read/Edit/Write
│ 2. # Instructions                    │  ← 操作指南
│    ├─ 文件创建前先 ls                │
│    ├─ 引号包裹含空格路径             │
│    ├─ 保持 cwd 用绝对路径            │
│    ├─ 超时设置（默认 2min/最大 10min）│
│    ├─ run_in_background 后台执行     │
│    ├─ 多命令发送策略                 │
│    ├─ Git 命令子项                   │
│    └─ 避免不必要的 sleep             │
│ 3. ## Command sandbox（可选）         │  ← 沙盒限制 JSON
│ 4. # Committing changes with git     │  ← 完整提交/PR 流程
│ 5. # Creating pull requests          │  ← PR 创建流程
│ 6. # Other common operations         │
└──────────────────────────────────────┘
```

### 2.0.2 工具替代指令（原文）

```
IMPORTANT: Avoid using this tool to run `find`, `grep`, `cat`, `head`,
`tail`, `sed`, `awk`, or `echo` commands, unless explicitly instructed
or after you have verified that a dedicated tool cannot accomplish your task.

 - File search: Use Glob (NOT find or ls)
 - Content search: Use Grep (NOT grep or rg)
 - Read files: Use Read (NOT cat/head/tail)
 - Edit files: Use Edit (NOT sed/awk)
 - Write files: Use Write (NOT echo >/cat <<EOF)
 - Communication: Output text directly (NOT echo/printf)
```

> **注意**：当 `hasEmbeddedSearchTools()` 为 true（ant 原生构建）时，Glob/Grep 被移除，`find`/`grep` 不再被禁止。

### 2.0.3 多命令策略指令（原文）

```
When issuing multiple commands:
  - If independent and can run in parallel → multiple Bash tool calls
    in a single message
  - If dependent, must run sequentially → single Bash call with '&&'
  - Use ';' only when you don't care if earlier commands fail
  - DO NOT use newlines to separate commands
```

### 2.0.4 Sleep 指令（完整原文）

```
Avoid unnecessary `sleep` commands:
  - Do not sleep between commands that can run immediately — just run them.
  - If your command is long running and you would like to be notified
    when it finishes — use `run_in_background`. No sleep needed.
  - Do not retry failing commands in a sleep loop — diagnose the root cause.
  - If waiting for a background task you started with `run_in_background`,
    you will be notified when it completes — do not poll.
  - If you must poll an external process, use a check command
    (e.g. `gh run view`) rather than sleeping first.
  - If you must sleep, keep the duration short (1-5 seconds).
```

> 当 `feature('MONITOR_TOOL')` 开启时，会插入 Monitor 工具提示，并将裸 `sleep N`（N≥2）阻塞。

### 2.0.5 Sandbox 段

当 `SandboxManager.isSandboxingEnabled()` 时动态插入，包含：
- **Filesystem** 限制（read.denyOnly / write.allowOnly）
- **Network** 限制（allowedHosts / deniedHosts）
- `$TMPDIR` 使用指令（替代 `/tmp`）
- `dangerouslyDisableSandbox` 使用条件（仅当看到 sandbox 失败证据时重试）

### 2.0.6 Git Safety Protocol（完整原文）

```
Git Safety Protocol:
- NEVER update the git config
- NEVER run destructive git commands (push --force, reset --hard,
  checkout ., restore ., clean -f, branch -D) unless the user explicitly
  requests these actions
- NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user
  explicitly requests it
- NEVER run force push to main/master, warn the user if they request it
- CRITICAL: Always create NEW commits rather than amending, unless the user
  explicitly requests a git amend. When a pre-commit hook fails, the commit
  did NOT happen — so --amend would modify the PREVIOUS commit
- When staging files, prefer adding specific files by name rather than
  using "git add -A" or "git add ."
- NEVER commit changes unless the user explicitly asks you to
```

### 2.0.7 ant 用户 vs 外部用户的 Git 段差异

| 方面 | ant 用户 | 外部用户 |
|------|---------|---------|
| 提交流程 | 指向 `/commit` 和 `/commit-push-pr` skill | 完整 4 步内联指令（git status → diff → commit → verify） |
| PR 流程 | 指向 `gh` 命令 | 完整 3 步 `gh pr create` 内联指令 |
| 归属签名 | `getAttributionTexts()` 动态生成 | 同上，但 `Co-Authored-By` 包含模型名 |
| 长度 | ~15 行 | ~80 行 |

## 三、WebFetch 二级模型 Prompt

WebFetch 的核心流程是：获取网页 → 转 Markdown → **用小型快速模型处理**。二级模型 prompt 的完整模板：

```typescript
function makeSecondaryModelPrompt(
  markdownContent: string,
  prompt: string,
  isPreapprovedDomain: boolean,
): string {
  const guidelines = isPreapprovedDomain
    ? `Provide a concise response based on the content above.
       Include relevant details, code examples, and documentation
       excerpts as needed.`
    : `Provide a concise response based only on the content above.
       In your response:
       - Enforce a strict 125-character maximum for quotes
       - Use quotation marks for exact language from articles
       - You are not a lawyer and never comment on legality
       - Never produce or reproduce exact song lyrics.`

  return `
Web page content:
---
${markdownContent}
---

${prompt}

${guidelines}
`
}
```

**关键设计**：
- `isPreapprovedDomain`（预批准域名如 docs 站点）→ 宽松引用
- 非预批准域名 → **严格 125 字符引用限制**（版权保护）
- 禁止评论合法性、禁止复制歌词

## 四、各工具参数 Schema 详解

### Read 工具

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `file_path` | string | ✅ | 绝对路径 |
| `offset` | integer | ❌ | 起始行号（0-based） |
| `limit` | integer | ❌ | 读取行数，默认 2000 |
| `pages` | string | ❌ | PDF 页范围（如 "1-5"），最大 20 页/次 |

Prompt 重点：`isPDFSupported()` 动态决定是否包含 PDF 说明。

### Edit 工具

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `file_path` | string | ✅ | 绝对路径 |
| `old_string` | string | ✅ | 待替换文本（必须唯一） |
| `new_string` | string | ✅ | 替换后文本 |
| `replace_all` | boolean | ❌ | 替换所有出现（默认 false） |

Prompt 中的行号前缀格式取决于 `isCompactLinePrefixEnabled()`：
- 紧凑模式：`line number + tab`
- 默认模式：`spaces + line number + arrow`

### Write 工具

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `file_path` | string | ✅ | 绝对路径 |
| `content` | string | ✅ | 完整文件内容 |

### Grep 工具

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `pattern` | string | ✅ | ripgrep 正则模式 |
| `path` | string | ❌ | 搜索路径（默认 cwd） |
| `glob` | string | ❌ | 文件过滤（如 `"*.ts"`） |
| `type` | string | ❌ | 文件类型（如 `"js"`, `"py"`） |
| `output_mode` | enum | ❌ | `content` / `files_with_matches`（默认）/ `count` |
| `-A` / `-B` / `-C` | number | ❌ | 上下文行数 |
| `-i` | boolean | ❌ | 大小写不敏感 |
| `-n` | boolean | ❌ | 显示行号（默认 true） |
| `multiline` | boolean | ❌ | 跨行匹配 |
| `head_limit` | number | ❌ | 限制输出条数（默认 250） |
| `offset` | number | ❌ | 跳过前 N 条 |

### Bash 工具

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `command` | string | ✅ | 要执行的命令 |
| `description` | string | ❌ | 命令描述（UI 展示用，禁止用 "complex"/"risk"） |
| `timeout` | number | ❌ | 超时毫秒（最大 600000） |
| `run_in_background` | boolean | ❌ | 后台运行 |
| `dangerouslyDisableSandbox` | boolean | ❌ | 禁用沙盒（需证据才可使用） |

### WebSearch 工具

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `query` | string | ✅ | 搜索查询（≥2 字符） |
| `allowed_domains` | string[] | ❌ | 限制搜索域名 |
| `blocked_domains` | string[] | ❌ | 排除域名 |

Prompt 动态注入 `getLocalMonthYear()` 确保模型使用正确年份。

### WebFetch 工具

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `url` | string (URI) | ✅ | 完整 URL |
| `prompt` | string | ✅ | 提取信息的提示 |

## 五、工具 Prompt 核心设计模式

### 5.1 工具引导（Tool Steering）⭐

> [!tip] 工具选择路由网络
> 每个工具明确告诉模型"什么时候用"和"什么时候不用"，形成互斥推荐图。这比在 system prompt 中集中罗列工具选择规则更高效。

每个工具明确告诉模型**什么时候用**和**什么时候不用**：

```
Bash → "Avoid find/grep/cat, use Glob/Grep/Read instead"
Grep → "Use Agent for open-ended multi-round searches"
Agent → "Use Read/Glob for simple lookups instead"
EnterPlanMode → "Use Agent for pure research"
WebFetch → "Prefer MCP tools or gh CLI for GitHub"
```

这形成了一个**工具选择路由网络**，减少模型选错工具的概率。

### 5.2 防御性编程指令

**Git Safety Protocol**（嵌入 Bash prompt）：
- NEVER update git config
- NEVER destructive git commands unless explicit
- NEVER skip hooks
- NEVER force push main/master
- CRITICAL: New commits rather than amending
- NEVER commit unless asked

### 5.3 并行执行暗示

多个 prompt 反复强调：
```
Bash: "independent commands → multiple Bash calls in single message"
Agent: "Launch multiple agents concurrently whenever possible"
Git: "Run the following in parallel, each using the Bash tool"
```

### 5.4 延迟加载（ToolSearch 机制）

性能优化：延迟工具只显示名称（无 schema），模型需先调用 `ToolSearch` 获取完整 schema。

```
MCP 工具 → 总是延迟
shouldDefer=true → 延迟
alwaysLoad=true → 永不延迟
ToolSearch/BriefTool/Agent(fork) → 永不延迟
```

### 5.5 动态 Prompt 生成

| 工具 | 动态内容 |
|------|---------|
| Bash | 根据 `hasEmbeddedSearchTools()` 决定提到哪些工具 |
| Agent | 根据 `isForkSubagentEnabled()` 切换示例 |
| Config | 从 `SUPPORTED_SETTINGS` 动态生成设置列表 |
| WebSearch | 动态插入当前年月 |
| Cron | 根据 `isDurableCronEnabled()` 展示持久化选项 |

### 5.6 ant vs 外部用户差异

| 方面 | ant 用户 | 外部用户 |
|------|---------|---------|
| EnterPlanMode | 更短，偏向 "just do it" | 更长，详细使用场景 |
| Git 操作 | 指向 `/commit` skill | 完整内联指令 |
| Agent 嵌套 | 允许 | 不允许 |
| Explore 模型 | inherit | haiku |
| Edit | "Use smallest old_string" | 无此提示 |

### 5.7 描述字段的双重角色

Bash `description` 参数同时是：
1. **用户体验**：UI 中显示命令做了什么
2. **行为约束**：禁止用 "complex"/"risk" 等词，强制简洁主动语态

**完整 Schema 定义原文**（`src/tools/BashTool/BashTool.tsx:230-240`）：

```typescript
description: z.string().optional().describe(
  `Clear, concise description of what this command does in active voice.
   Never use words like "complex" or "risk" in the description - just
   describe what it does.

   For simple commands (git, npm, standard CLI tools), keep it brief (5-10 words):
   - ls → "List files in current directory"
   - git status → "Show working tree status"

   For commands that are harder to parse at a glance (piped commands,
   obscure flags, etc.), add enough context to clarify what it does:
   - find . -name "*.tmp" -exec rm {} \\; → "Find and delete all .tmp files recursively"
   - git reset --hard origin/main → "Discard all local changes and match remote main"`),
```

**设计理由**：description 放在 Zod schema 的 `.describe()` 中——这意味着**它是 tool schema 的一部分，会随工具定义发送给 API**。模型在决定如何填写 description 时，这些指令就是它的约束。禁止 "complex"/"risk" 不仅让 UI 更清晰，还防止模型用模糊词汇隐藏破坏性操作的本质（如 `git reset --hard` 应描述为 "Discard all local changes" 而非 "complex git operation"）。

## 六、工具过滤与组装

```
getAllBaseTools()          → 全部基础工具
    ↓
getTools(permissionCtx)   → 过滤禁用/拒绝的工具
    ↓
assembleToolPool()        → 合并内置 + MCP，去重排序
    ↓
useMergedTools()          → 最终工具池
```

### 子代理工具限制

```
Coordinator 模式: 仅 Agent, SendMessage, TaskStop
Simple 模式: 仅 Bash, Read, Edit
Explore/Plan Agent: 禁止 Agent, Edit, Write, NotebookEdit, ExitPlanMode
```

## 七、Verification Agent 的 Prompt 设计亮点

这是所有 prompt 中最有深度的对抗性设计：

1. **自我反省机制**："你会感到跳过检查的冲动。识别并做相反的事"
2. **反合理化**：列出 LLM 常见偷懒借口（"代码看起来对的"、"测试已通过"）
3. **强制证据**：每个检查必须有实际命令和输出，不接受"阅读代码"
4. **对抗性探测**：至少一个对抗性测试（并发、边界值、幂等性）
5. **最终裁决**：`VERDICT: PASS | FAIL | PARTIAL`

## 八、实践启示

### 工具 Prompt 设计模式可复用

1. **工具路由网络**：每个工具 prompt 明确指向其他更合适的工具，形成"互斥推荐图"。这比在 system prompt 中集中罗列工具选择规则更高效——每次工具调用时模型都能看到上下文相关的推荐。
2. **防御性重复**：Git Safety Protocol 在 Bash prompt 中重复了 6 条 NEVER 规则。这不是冗余——它利用了 LLM 对"最近上下文"更敏感的特性，将关键约束放在工具调用时而非遥远的 system prompt 中。
3. **动态 prompt 生成优于静态模板**：Bash prompt 根据 `hasEmbeddedSearchTools()`、`shouldIncludeGitInstructions()`、`SandboxManager.isSandboxingEnabled()` 等运行时条件组装，避免向模型展示不相关的指令（减少混淆和 token 消耗）。
4. **description 参数的双重作用**值得借鉴：一个字段同时服务 UI 展示和行为约束（禁用特定词汇），是 prompt engineering 和产品设计的优雅交叉点。

### WebFetch 的版权保护设计

二级模型 prompt 区分"预批准域名"和"一般域名"，后者强制 125 字符引用限制——这是将法律合规要求编码到 prompt 层的范例。可以推广到任何需要对外部内容做合规处理的 AI 应用。

### Sandbox prompt 的信任分级

Sandbox 指令不是简单的"允许/禁止"，而是引导模型在"看到 sandbox 失败证据后立即重试 `dangerouslyDisableSandbox: true`"——这种"渐进式信任升级"模式比一刀切更灵活，可应用于任何需要安全分级的 agent 系统。
